package com.neteast.video.view;
import com.neteast.video.GlobalConstant;
import com.neteast.video.R;
import com.neteast.video.activity.MainActivity;
import android.app.AlertDialog.Builder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

public class VideoWebView extends WebView{
	
	private Context mContext;
	private WebSettings mSettings;
	private MainActivity activity;
	//public boolean isLoad=false;
	private LoadStateListener loadState;
	public interface LoadStateListener{
		public void loadsuccessful(int progress);
	}
	
	public void setLoadStateListener(LoadStateListener loadState){
		this.loadState = loadState;
	}
	
	public VideoWebView(Context context) {
		super(context,null,R.style.webStyle);
		mContext=context;
		this.activity=(MainActivity) context;
		init();
	}
	
	private void init() {
		setConfigure();
		addClient();
		initDialog();
		addJavascriptInterface(new JsInterface(), "sw");
	}
	
	
	private void setConfigure() {
		setFocusable(false);
		mSettings=this.getSettings();
		mSettings.setJavaScriptEnabled(true);
		mSettings.setAllowFileAccess(true);
		mSettings.setPluginsEnabled(true);
		mSettings.setPluginState(PluginState.ON);
		mSettings.setLoadWithOverviewMode(true);
		mSettings.setUseWideViewPort(true);
		mSettings.setDomStorageEnabled(true);
		String path = mContext.getDir("localstorage", Context.MODE_PRIVATE).getPath();
		mSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		mSettings.setDatabaseEnabled(true);
		mSettings.setDatabasePath(path);
		this.setVerticalScrollBarEnabled(false);
		this.setHorizontalScrollBarEnabled(false);
	}
	
	
	private void addClient() {
		this.setWebViewClient(mWebViewClient);
		this.setWebChromeClient(chromeClient);
	}
	
	
	
	
	private void initDialog() {
		searchDialog = new SearchDialog(mContext, R.style.dialog);
		final EditText etValue=(EditText) searchDialog.getView().findViewById(R.id.ed_search_value);
		searchDialog.getView().findViewById(R.id.btn_search).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String value = etValue.getText().toString();
				if (TextUtils.isEmpty(value.trim())) {
					Toast.makeText(mContext, "关键字不能为空", 300).show();
					return;
				}
				VideoWebView.this.loadUrl("javascript:movieSearch('"+value+"')");
				searchDialog.dismiss();
			}
		});
		
		loginDialog = new AlertDialog.Builder(mContext).setTitle("您还没有登录，请先登录。")
				.setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent=new Intent();
						intent.setAction("com.neteast.androidclient.newscenter.login");
//						intent.putExtra("pkg", "com.neteast.video");
//						intent.putExtra("cls", "com.neteast.video.activity.MainActivity");
						activity.startActivity(intent);
						loginDialog.dismiss();
					}
				}).create();
	}
	
	
	private WebChromeClient chromeClient=new WebChromeClient(){
		public void onProgressChanged(WebView view, int newProgress) {
				loadState.loadsuccessful(newProgress);
		}
	};
	
	private WebViewClient mWebViewClient=new WebViewClient(){
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			
			if (url.startsWith("ydsw://")) {
				url=url.substring(7);
			}
			String nUrl=url.toLowerCase();
			if (nUrl.endsWith(".3gp")||nUrl.endsWith(".wmv")||nUrl.endsWith(".mp4")) {
				Intent intent=new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse(url), "video/*");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(intent);
				return true;
			}
			if (nUrl.endsWith(".mp3")) {
				Intent intent=new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse(url), "audio/mp3");
				mContext.startActivity(intent);
				return true;
			}
			view.loadUrl(url);
			return true;
		}
	};
	private SearchDialog searchDialog;
	private AlertDialog loginDialog;
	
	/**
	 * 与js进行通信的接口类
	 * @author tiangh
	 *
	 */
	@SuppressWarnings("unused")
	private class JsInterface{
		public void AndroidAlert(String msg) {  
			Dialog dialog;
			AlertDialog.Builder builder=new Builder(mContext);
			builder.setTitle("提示")
					.setMessage(msg)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog=builder.create();
			dialog.show();
        }  
        
        public void AndroidConfirm(String msg, final String functionName){
        	Dialog dialog;
			AlertDialog.Builder builder=new Builder(mContext);
			builder.setTitle("提示")
					.setMessage(msg)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							VideoWebView.this.loadUrl("javascript:"+functionName);
							dialog.dismiss();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog=builder.create();
			dialog.show();
        }
        
        public void AndroidShow(String msg,int x,int y) {  
			Toast toast=Toast.makeText(mContext,msg, Toast.LENGTH_LONG);	
			if ((x!=-1) && (y!=-1))
			  toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, x, y);
			toast.show();
        }
        public void showSearchDialog(){
        	searchDialog.show();
        }
        public void hiddenSearchDialog(){
        	searchDialog.dismiss();
        }
        
        public String getUserInfo() {
        	Uri uri = Uri.parse("content://com.neteast.androidclient.newscenter/info");
    		Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null);
    		if(cursor != null){
    			if (cursor.moveToFirst()) {
    				int userid = cursor.getInt(cursor.getColumnIndex("userid"));
    				String token = cursor.getString(cursor.getColumnIndex("token"));
    				Log.i("test", "userid="+userid);
    				Log.i("test", "token="+token);
    				//登录
    				if (userid!=0) {
    					return userid+"|"+token;
    				}
    			}
    			loginDialog.show();
				return "0|null";
    		}else{
    			Toast.makeText(mContext, "未找到消息盒子", Toast.LENGTH_LONG).show();
    			return "0|null";
    		}
		}
        
        public void finishApplication(){
        	activity.showDialog(GlobalConstant.MAIN_DIALOG_EXIT);
        }
	}
}
